from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.contrib.auth.hashers import make_password,check_password

# 图书商城前台登陆页面
def login(request):
    return render(request,'myhome/login/login.html')
def dologin(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # nextpath = request.GET.get('nextpath','/')

    # 通过手机号获取用户对象
    obj = models.Users.objects.filter(phone=data['phone'])
    if obj.count() == 0:
        return HttpResponse('<script>alert("账号或密码错误");history.back();</script>')

    # 完成登陆操作
    from django.contrib.auth.hashers import make_password
    if make_password(data['password'],obj[0].password):
        request.session['VipUser'] = {'id':obj[0].id,'phone':obj[0].phone}
        return HttpResponse(f'<script>alert("欢迎登陆！！"); location.href="/"</script>')
    else:
        return HttpResponse('<script>alert("账号或密码错误");history.back();</script>')
    # return HttpResponse('执行登陆')

def logout(request):
    request.session.flush()
    return HttpResponse('<script>alert("退出成功"); location.href="/login"</script>')
# 注册页面
def register(request):
    return render(request,'myhome/login/register.html')
# 执行注册登陆
def doregister(request):
    data = {}
    data['phone'] = request.POST.get('phone')
    data['password'] = request.POST.get('password')
    # 插入数据库
    obj = models.Users(**data)
    obj.save()

    return HttpResponse('<script>alert("注册成功，欢迎登陆"); location.href="/login"</script>')

def checkphone(request):
    # 接收
    phone = request.GET.get('phone')
    # 验证
    n = models.Users.objects.filter(phone=phone).count()

    if n:
        return JsonResponse({'code':1,'msg':'手机号码已存在'})
    else:
        return JsonResponse({'code':0,'msg':'手机号码可注册'})

def shenphone(request):
    # 接收手机号码
    phone = request.GET.get('phone')
    vcode = request.randint(10000,99999)

    # 发送短信验证码
    # url = 'https://open.ucpaas.com/ol/sms/sendsms'
    # data = {
    #     "sid":"39467b989d087c2d92c6132184a365d8",
    #     "token":"23f757bad208226ec301e117e40006ed",
    #     "appid":"2d92c6132139467b989d087c84a365d8",
    #     "templateid":"154501",
    #     "param":"87828,3",
    #     "mobile":"18011984299"
    # }

    return JsonResponse({'cose':0,'msg':'短信验证码已发送，请查收','vcode':123456})